import {
  getGoodsDetail
} from './network/goodsDetail.js';
$(function() {
  class GoodsDetail {
    constructor() {
      if(!location.hash.split('=')[1]) {
        alert('商品id不存在，请重新选择商品');
        location.href = `./goodsList.html`;
      }
      this.init();
    } 
    init() {
      this.id = cookie('id') ? cookie('id') : null;
      this.token = cookie('token') ? cookie('token') : null;
      this.initDom();
      new Promise((resolve, reject) => {
        this.loadGoodsDetailData(resolve);
      }).then(() => {      
        //获取所有参数item
        this.params_items = $('.goods-detail .left-detail .params-container li.params');
        this.showSmallBtns();
        new Magnifier('.goods-detail .left-detail .img-detail .img', '.goods-detail .left-detail .img-detail .img > img', '.goods-detail .left-detail .img-detail .img .bigImg > img', '.goods-detail .left-detail .img-detail .img .mask', '.goods-detail .left-detail .img-detail .img .bigImg');
        this.bindEvent();
      })
    }
    initDom() {
      //获取小图容器
      this.imgBox = $('.goods-detail .left-detail .img-detail .img');
      //获取小图
      this.img = $('.goods-detail .left-detail .img-detail .img > img');
      //获取大图
      this.bigImg = $('.goods-detail .left-detail .img-detail .img .bigImg > img');
      //获取遮罩层
      this.mask = $('.goods-detail .left-detail .img-detail .img .mask');
      //获取大图显示区
      this.bigImgBox = $('.goods-detail .left-detail .img-detail .img .bigImg');
      //获取轮播图片容器
      this.smallImgs = $('.goods-detail .left-detail .img-list ul');
      //获取标题
      this.title = $('.goods-detail .left-detail .title');
      //获取价格
      this.price = $('.goods-detail .left-detail .main-box .price .price-text');
      //获取销量
      this.sales = $('.goods-detail .left-detail .main-box .sales .sales-count');
      //获取评论数
      this.ccount = $('.goods-detail .left-detail .main-box .comment .comment-count');
      //获取参数容器
      this.params_container = $('.goods-detail .left-detail .params-container');
      //获取库存容器
      this.totalStock = $('.goods-detail .left-detail .store .store-text');
      //获取计数器
      this.counter = $('.goods-detail .left-detail .counters');
      //商品详情，商品描述
      this.desc = $('.product-detail .goods-desc .content'); 
      //商品参数
      this.sDetailsParams = $('.product-detail .goods-params .content');
      //获取尺寸表格
      this.size_rules_table = $('.product-detail .size-rules table.content');
      //获取表格下的提示
      this.size_tip = $('.product-detail .size-rules .tip');
      //效果图列表
      this.effect_list = $('.product-detail .effects ul.content');
      //获取小图容器
      this.smallImgsWrap = $('.goods-detail .left-detail .img-list ul');
      //获取小图轮播的左右按钮
      this.smallprev = $('.goods-detail .left-detail .img-list-wrap .prev');
      this.smallnext = $('.goods-detail .left-detail .img-list-wrap .next');

      //获取选项卡标题
      this.tabtitles = $('.product-params ul.title li');
      //获取选项卡内容
      this.tabcontents = $('.product-params ul.content li');

      //评论区
      this.rateArea = $('.product-params .content li.comment ul.content');
      //加入购物车
      this.turnIntoCart = $('#turn-into-cart');
      //跳转购物车弹窗
      this.gotocart = $('.go-to-cart');
      //获取弹窗关闭按钮
      this.toastclose = $('.go-to-cart .close');
      //获取弹窗去购物车按钮
      this.gotocart_btn = $('.go-to-cart .but button.gotocart');
      //获取弹窗留在本页按钮
      this.stayhere_btn = $('.go-to-cart .but button.stayhere');
    }
    //绑定事件
    bindEvent() {
      let _this = this;
      //计数器事件
      this.counter.on('click', 'div', function() {
        if($(this).hasClass('dec')) {
          let value = $(this).siblings('input').val().trim();
          if(value <= 1) {
            return;
          }
          value--;
          $(this).siblings('input').val(value);
        }else if($(this).hasClass('inc')) {
          let value = $(this).siblings('input').val();
          if(parseInt(value) >= parseInt(_this.totalStock.text())) {
            return;
          }
          value++;
          $(this).siblings('input').val(value);
        }
      });
      this.counter.on('change', 'input', function() {
        let value = $(this).val().trim();
        if(value < 1) {
          $(this).val('1');
          new Toast({
            message: `Sorry, 你连1件都不买, 我们很为难哦, 帮你设置买1件了哦~`,
            color: '#E6A23C'
          });
        }else if(parseInt(value) > parseInt(_this.totalStock.text())) {
          $(this).val(_this.totalStock.text());
          new Toast({
            message: `Sorry, 库存只有${_this.totalStock.text()}件了哦, 已经帮你设为最多了~`,
            color: '#E6A23C'
          });
        }
      });
      //小图hover切换
      this.smallImgsWrap.on('mouseover', 'li', function() {
        let src = $(this).children('img').prop('src');
        _this.img.prop('src', src);
        _this.bigImg.prop('src', src);
      });
      //小图左滑
      this.smallprev.on('click', function() {
        _this.smallnext.css('display', 'block');
        $(this).css('display', 'none');
        _this.smallImgsWrap.stop(true).animate({
          left: 0
        });
      });
      //小图右滑
      this.smallnext.on('click', function() {
        _this.smallprev.css('display', 'block');
        $(this).css('display', 'none');
        _this.smallImgsWrap.stop(true).animate({
          left: -350
        });
      });
      //参数选中效果
      this.params_container.on('click', '.params-list li', function() {
        $(this).addClass('active').siblings().removeClass('active');
        $(this).parents('li.params').attr('data-select', true);
      });
      //选项卡切换
      this.tabtitles.on('click', function() {
        $(this).addClass('active').siblings().removeClass('active');
        let index = $(this).index();
        _this.tabcontents.eq(index).addClass('current').siblings().removeClass('current');
      });
      //加入购物车
      this.turnIntoCart.on('click', function() {
        if(_this.token && _this.id) {
          let flag = true;
          $('li.params').each((i, ele) => {
            if(!$(ele).attr('data-select')) {
              flag = false;
              new Toast({
                message: '请选择必要的参数',
                color: '#E6A23C'
              });
            }
          });
          if(flag) {
            let cartParams = _this.putCartOptions();
            localStorage.setItem(_this.id, JSON.stringify(cartParams));
            _this.flayCart();
          }
        }else {
          new Toast({
            message: '用户未登陆或认证已过期，请您登录后再进行操作',
            color: '#E6A23C',
            callback() {
              location.href = './login.html';
            }
          });
        }
      });
      //关闭弹窗
      this.toastclose.on('click', function() {
        _this.fadeOutToast();
      });
      this.stayhere_btn.on('click', function() {
        _this.fadeOutToast();
      });
      //去购物车
      this.gotocart_btn.on('click', function() {
        location.href = `./shopCart.html`;
      });
    }

    //将商品规格参数转化为对象
    transformParams() {
      let goods_params = [];
      for(let i=0; i<this.params_items.length; i++) {
        let key = this.params_items.eq(i).find('span.params-title').text().trim().slice(0, -1);
        let value = '';
        this.params_items.eq(i).find('.params-list li').each((i, ele) => {
          if($(ele).hasClass('active')) {
            value = $(ele).text().trim();
          }
        });
        goods_params.push([key, value]);
      }
      return Object.fromEntries(goods_params);
    }
    //填入购物车参数对象
    putCartOptions() {
      let paramsObj = this.transformParams();
      if(localStorage.getItem(this.id)) {
        let flag = true;
        let goodsid = location.hash.split('=')[1];
        for(let i=0; i<JSON.parse(localStorage.getItem(this.id)).length; i++) {
          if(goodsid === JSON.parse(localStorage.getItem(this.id))[i].goodsid && JSON.stringify(JSON.parse(localStorage.getItem(this.id))[i].params) === JSON.stringify(paramsObj)) {
            let number = parseInt(this.counter.find('input').val().trim());
            let arr = JSON.parse(localStorage.getItem(this.id));
            arr[i].count = parseInt(arr[i].count) + number;
            flag = false;
            return arr;
          }
        }
        if(flag) {
          let arr = JSON.parse(localStorage.getItem(this.id));
          arr.push({
            img: this.img.prop('src'),
            goodsid: location.hash.split('=')[1],
            count: parseInt(this.counter.find('input').val().trim()),
            title: this.title.text(),
            unit_price: this.price.text(),
            store: this.totalStock.text(),
            params: paramsObj
          });
          return arr;
        }
      }else {
        return [{
          img: this.img.prop('src'),
          goodsid: location.hash.split('=')[1],
          count: parseInt(this.counter.find('input').val().trim()),
          title: this.title.text(),
          unit_price: this.price.text(),
          store: this.totalStock.text(),
          params: paramsObj
        }]
      }
    }
    //小图轮播按钮显示
    showSmallBtns() {
      let length = $('.goods-detail .left-detail .img-list ul li').length;
      if(length > 5) {
        this.smallnext.css('display', 'block');
      }
    }
    //获取商品详情数据
    async loadGoodsDetailData(resolve) {
      let res = await getGoodsDetail();
      let data = this.contrast(res.data);
      this.renderGoodsDetail(data);
      resolve();
    }
    //将商品详情所有数据与当前商品id比对
    contrast(res) {
      let goodsId = location.hash.split('=')[1];
      for(let i=0; i<res.length; i++) {
        if(res[i].data.result.itemInfo.itemId === goodsId) {
          return res[i].data.result;
        }
      }
    }
    //渲染
    renderGoodsDetail(res) {
      document.title = res.itemInfo.seo.title ? res.itemInfo.seo.title : '商品详情页面';
      this.renderImgs(res);
      this.renderImgsList(res);
      this.renderInfo(res);
      this.renderSDetails(res);
      this.renderRate(res);
    }
    //渲染大图和小图
    renderImgs(res) {
      this.img.prop('src', res.skuInfo.img);
      this.bigImg.prop('src', res.skuInfo.img);
    }
    //渲染小图列表
    renderImgsList(res) {
      this.smallImgsList = res.topImages;
      this.smallImgs.html(res.topImages.map(item => {
        return `
          <li>
            <img src="${item}">
          </li>
        `
      }).join(''));
    }
    //渲染商品详情
    renderInfo(res) {
      this.title.text(res.itemInfo.title);
      this.price.text(res.itemInfo.highNowPrice);
      this.sales.text(res.rateInfo.sales);
      this.ccount.text(res.rateInfo.cRate);
      //渲染商品参数
      this.params_container.html(res.skuInfo.props.map(item => {
        return `
        <li class="params clearfix">
        <span class="params-title fl">${item.label}：</span>
        <ul class="params-list">
          ${item.list.map(value => {
            return `
              <li>${value.name}</li>
            `;
          }).join('')}
        </ul>
      </li>
        `;
      }).join(''));
      this.totalStock.text(res.skuInfo.totalStock);
    }
    //渲染商品底部详情信息
    renderSDetails(res) {
      this.desc.text(res.detailInfo.desc);
      //渲染商品参数
      if(res.itemParams.info.set) {
        let sDetailsParamsStr = ``;
        for(let attr in res.itemParams.info.set) {
          sDetailsParamsStr += `<li>${attr} : ${res.itemParams.info.set[attr]}</li>`;
        }
        this.sDetailsParams.html(sDetailsParamsStr);
      }

      //渲染商品尺寸表格
      if(res.itemParams.rule) {
        let size_rules = ``;
        for(let i=0; i<res.itemParams.rule.tables[0].length; i++) {
          size_rules += `<tr>`;
          for(let j=0; j<res.itemParams.rule.tables[0][i].length; j++) {
            size_rules += `<td>${res.itemParams.rule.tables[0][i][j]}</td>`;
          }
          size_rules += `</tr>`;
        }
        this.size_rules_table.html(size_rules);
        //渲染表格下的提示
        this.size_tip.text(res.itemParams.rule.disclaimer);
      }
      //渲染效果图
      this.effect_list.html(res.detailInfo.detailImage[0].list.map(item => {
        return `
          <li>
            <img src="${item}">
          </li>
        `;
      }).join(''));
    }
    //渲染评论
    renderRate(res) {
      if(res.rateInfo.list) {
        this.rateArea.html(res.rateInfo.list.map(item => {
          return `
          <li class='clearfix'>
            <div class="avatar fl">
              <img src="${item.user.avatar ? item.user.avatar : ''}" alt="">
            </div>
            <div class="cinfo fl">
              <div class="uname">${item.user.uname ? item.user.uname : ''}</div>
              <div class="rate">
                ${item.content ? item.content : ''}
              </div>
              <div class="size-info">
                ${item.extraInfo ? item.extraInfo.join(', ') : ''}
              </div>
              <ul class="photos clearfix">
                ${item.image ? item.images.map(img => {
                  return `
                    <li>
                      <img src="${img}">
                    </li>
                  `;
                }).join('') : ''}
              </ul>
            </div>
          </li>
          `;
        }).join(''));
      }
    }
    //购物车动画
    flayCart() {
      let flybox = $('<img class="flycart" src="../static/images/shopcart/flyCart.png" alt="">');
      $('body').append(flybox);
      let left = this.turnIntoCart.offset().left + this.turnIntoCart.outerWidth() / 2 - flybox.width() / 2;
      let top = this.turnIntoCart.offset().top + this.turnIntoCart.outerHeight() / 2 - flybox.height() / 2;
      flybox.css({
        display: 'block',
        left,
        top
      });
      let asidecut = $('.aside-shortcut').offset();
      let stickyheader = $('#sticky-header').outerHeight();
      flybox.stop(true).animate({
        left: asidecut.left - flybox.width(),
        top: stickyheader + $(document).scrollTop()
      }, () => {
        flybox.remove();
        this.gotocart.stop(true).slideDown()
      });
    }
    //弹窗淡出
    fadeOutToast() {
      this.gotocart.stop(true).fadeOut();
    }
  }

  class DetailFloors {
    constructor() {
      //获取所有电梯按钮
      this.btns = $('.floors-wrapper .floors ul li');
      //获取所有楼梯层
      this.floors = $('.product-detail .floor');
      this.flag = true;
      this.bindEvent();
      $(window).triggerHandler('scroll');
    }
    bindEvent() {
      let _this = this;
      this.btns.on('click', function() {
        this.flag = false;
        $(this).addClass('current').siblings().removeClass('current');
        let index = $(this).index();
        $('html,body').stop(true).animate({
          scrollTop: _this.floors.eq(index).offset().top -70
        }, () => {
          _this.flag = true;
        });
      });
      $(document).on('scroll', function() {
        if(_this.flag) {
          _this.floors.each((index, item) => {
            if($(document).scrollTop() + 70 >= $(item).offset().top - 1) {
              _this.btns.eq(index).addClass('current').siblings().removeClass('current');
            }
          });
        }
      });
    }
  }
  new GoodsDetail();
  new DetailFloors();
});

